package com.hd.trans.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.Window;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;

import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.framework.dialog.LanguageDialog;
import com.hd.trans.framework.dialog.LanguageDialogType;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.limit4Use.LimitUseListener;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.ui.base.LimitBaseActivity;
import com.hd.trans.ui.fragment.SimulBaseFragment;
import com.hd.trans.ui.fragment.SimulInterpretFragment3;
import com.hd.trans.ui.fragment.SimulNormalFragment3;
import com.hd.trans.ui.model.SimultaneousModel;
import com.hd.trans.utils.AnimType;
import com.hd.trans.utils.NotificationUtil;
import com.hd.trans.utils.TrackerForTrans;

import java.util.Objects;
/**
 * 智能翻译官定制版
 */
public class SimulHomeActivity3 extends LimitBaseActivity {

    private FrameLayout rootView;
    public static final int NORMAL = 0;
    public static final int TOP = 1;
    public static final int BOTTOM = 2;
    public SimultaneousModel mDataModel;
    public static boolean mOpenSceneTransition = false;
    public static AnimType animType = AnimType.normal;
    Fragment targetFragment = null;
    public boolean isTopStyle;
    private static int theme = 1;

    public static void open(Context context, LimitUseListener listenner) {
        setLimitListener(listenner);
        Intent intent = new Intent(context, SimulHomeActivity3.class);
        context.startActivity(intent);
    }

    /**
     * @param themeValue 主题，值:0或1
     */
    public static void open(Context context, LimitUseListener listenner, int themeValue) {
        setLimitListener(listenner);
        if(themeValue >= 0){
            theme = themeValue;
        }
        Intent intent = new Intent(context, SimulHomeActivity3.class);
        context.startActivity(intent);
    }

    /**
     * @param themeValue 主题，值:0或1
     */
    public static void open(Context context, LimitUseListener listenner, Bundle options, int themeValue) {
        setLimitListener(listenner);
        mOpenSceneTransition = options!= null;
        if(themeValue >= 0){
            theme = themeValue;
        }
        Intent intent = new Intent(context, SimulHomeActivity3.class);
        context.startActivity(intent,options);
    }

    /**
     * 共享元素动画
     */
    public static void open(Activity context, LimitUseListener listenner, Bundle options) {
        setLimitListener(listenner);
        mOpenSceneTransition = options!= null;
        Intent intent = new Intent(context, SimulHomeActivity3.class);
        context.startActivity(intent,options);
    }

    /**
     * 底部弹窗动画
     */
    public static void openBottomIn(Activity context, LimitUseListener listenner) {
        openBottomIn(context, null, null , listenner);
    }

    /**
     * 底部弹窗动画
     */
    public static void openBottomIn(Activity context, String fromLang, String toLang, LimitUseListener listenner) {
        setLimitListener(listenner);
        Intent intent = new Intent(context, SimulHomeActivity3.class);
        intent.putExtra("fromLang", fromLang);
        intent.putExtra("toLang", toLang);
        context.startActivity(intent);
        animType = AnimType.bottom;
        context.overridePendingTransition(R.anim.trans_bottom_in, R.anim.trans_no_change);
    }

    /**
     * 中间进场动画
     */
    public static void openCenterIn(Activity context, LimitUseListener listenner) {
        setLimitListener(listenner);
        animType = AnimType.center;
        Intent intent = new Intent(context, SimulHomeActivity3.class);
        context.startActivity(intent);
        context.overridePendingTransition(R.anim.trans_center_in, R.anim.trans_no_change);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_simul_frame;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature( Window.FEATURE_CONTENT_TRANSITIONS );
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mDataModel = new ViewModelProvider(this).get(SimultaneousModel.class);
        initView();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //埋点
        TranslationInterior.getTrackerListener().view(TrackerForTrans.TSCY + TrackerForTrans.SY);
    }

    private void initData() {

        String fromLangName = getIntent().getStringExtra("fromLang");
        String toLangName = getIntent().getStringExtra("toLang");

        if(TextUtils.isEmpty(fromLangName) || TextUtils.isEmpty(toLangName)){
            fromLangName = PreferenceMgr.getInstance().getTranslatePreference().getVoiceFromLanguage();
            toLangName = PreferenceMgr.getInstance().getTranslatePreference().getVoiceToLanguage();

            changeFragment(NORMAL);
            isTopStyle = false;
        }else {
            isTopStyle = true;
            changeFragment(TOP);
        }

        mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName));
        mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName));

        NotificationUtil.getInstance().checkNotification(this);
    }


    public void changeFragment(int type) {
        switch (type) {
            case NORMAL:
                //targetFragment = new VoiceTransFragment();
                targetFragment = new SimulNormalFragment3(theme, mDataModel);
                break;
            case TOP:
                targetFragment = new SimulInterpretFragment3(mDataModel);
                break;
        }

        //直接替换的fragment,没有使用到懒加载。baseFragment随意改。
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_view, targetFragment, targetFragment.getClass().getName());
        if (type != NORMAL) {
            transaction.addToBackStack(targetFragment.getClass().getName());
            //申请权限
            requestAudioPermission(transaction::commitAllowingStateLoss);
        } else {
            //切换fragment
            transaction.commitAllowingStateLoss();
        }

    }


    public boolean isLimitUsed(String title){
        return !intercept(false, title, null, null);
    }

    //同语音翻译逻辑
    public boolean isLimitUsed(EventCode code) {
        return !intercept(code);
    }

    //如果翻译成功了。保存使用的时间。
    public void saveUseTime(long useLong) {
        consumeFreeTrialTime(useLong);
    }

    @Override
    public void finish() {
        super.finish();
        if(animType == AnimType.center){
            overridePendingTransition(R.anim.trans_no_change, R.anim.trans_center_out);
        }else if(animType == AnimType.bottom){
            overridePendingTransition(R.anim.trans_no_change, R.anim.trans_bottom_out);
        }else {
            overridePendingTransition(0, 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDataModel.getLanguageFrom().removeObservers(this);
        mDataModel.getLanguageTo().removeObservers(this);
    }

    //选择语言
    public void showLanguageDialog(boolean isFromPage) {
        /*SelectLanguageDialog.newInstance(mDataModel.getLanguageFrom().getValue(), mDataModel.getLanguageTo().getValue(), isFromPage, true, false)
                .setOnLanguageChangedListener((language, isFrom) -> {
                    if (isFrom) {
                        mDataModel.setLanguageFrom(language);
                    } else {
                        mDataModel.setLanguageTo(language);
                    }
                }).show(getSupportFragmentManager(), "VoiceHomeActivity");*/
        LanguageDialog dialog = new LanguageDialog(
                Objects.requireNonNull(mDataModel.getLanguageFrom().getValue()),
                Objects.requireNonNull(mDataModel.getLanguageTo().getValue()),
                isFromPage, LanguageDialogType.VOICE, LanguageDialogType.TO_VOICE);
        dialog.show(getSupportFragmentManager(),"LanguageDialog");
        dialog.setOnLanguageChangedListener((fromLanguage, toLanguage , selectedLanguage) -> {
            mDataModel.setLanguageFrom(fromLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveVoiceFromLanguage(fromLanguage.getName());
            mDataModel.setLanguageTo(toLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveVoiceToLanguage(toLanguage.getName());

            if(targetFragment instanceof SimulInterpretFragment3){
                ((SimulInterpretFragment3)targetFragment).changeHintText();
            }
        });
    }


    private void initView() {
        rootView = findViewById(R.id.fragment_view);
    }

    @Override
    public void onBackPressed() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_view);
        if(fragment instanceof SimulBaseFragment){
            SimulBaseFragment baseFragment = (SimulBaseFragment) fragment;
            if(baseFragment.onBackPressed()){
                return;
            }
        }
        super.onBackPressed();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_view);
        if(fragment instanceof SimulBaseFragment){
            SimulBaseFragment simulBaseFragment = (SimulBaseFragment) fragment;
            if(simulBaseFragment.dispatchTouchEvent(ev)){
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @NonNull
    @Override
    public EventCode getPageType() {
        return EventCode.SIMUL_TRANSLATE;
    }
}